<template>
    <view class="safe-area-inset-bottom">
        <view class="standard">
            <view class="top-bar">
                <view class="top-content">
                    <view class="left">
                        共
                        <text class="u-type-error">{{ isNaN(summaryCount) ? 0 : summaryCount }}</text>
                        件商品
                    </view>
                    <view class="right">
                        <text class="head">合计：</text>
                        <text>￥{{ Number(summaryPrice).toFixed(2) }}</text>
                    </view>
                </view>
            </view>
            <view class="holder" :style="{ height: topBarHeight + 'px' }"></view>
            <!-- 领型 -->
            <view class="collar_type safe-area-inset-bottom" v-if="collars.length > 1">
                <view class="title">
                    <text>选择款型</text>
                </view>
                <view class="collar_type-list" id="guide001">
                    <view v-for="(collar, index) in collars" :key="'__collar' + index" class="collar-wrapper">
                        <view class="collar-item" @click="setCollarNum(collar.name)">
                            <img-cache :src="`${global.productImageUrl}${collar.collarImage}/1`" width="100%" :height="ColorBtnWidth" border-radius="10rpx 10rpx 0 0" class="collar-image"></img-cache>
                            <view class="collar-name" :class="{ collarActived: currentCollar === collar.name }" style="letter-spacing: 2rpx">
                                <view>款号</view>
                                <view>{{ collar.modelNo }}</view>
                            </view>
                            <u-badge type="error" :count="collar.badge" :offset="[5, 5]" v-show="collar.badge > 0" bgColor="#fc4f75" :key="$u.guid(8)" class="badge"></u-badge>
                        </view>
                        <view class="limit-warning" v-if="getLimitState(collar)">
                            <text class="icon">&#xe631;</text>
                            <text>超出限购</text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="content safe-area-inset-bottom">
                <view class="title">
                    <text>选择颜色(长按图片预览)</text>
                </view>
                <view class="skus-color-btns" id="guide002">
                    <view v-for="(itm, idx) in currentColors" :key="'colorBtn' + idx" class="skus-color-item" @tap="changeColor(idx, itm)">
                        <view @longtap="showPreview(idx)">
                            <img-cache :src="itm.picId ? `${global.productImageUrl}${itm.picId}/1` : `/static/images/placeholder.png`" width="100%" :height="ColorBtnWidth" border-radius="10rpx 10rpx 0 0" class="sku-image"></img-cache>
                        </view>
                        <view class="skus-color-item-name">{{ itm.colorName }}</view>
                        <u-badge type="error" :count="itm.badge" :offset="[5, 5]" v-show="itm.badge > 0" bgColor="#fc4f75" class="badge" :key="$u.guid(8)"></u-badge>
                        <!-- 已抢光 -->
                        <view class="sale-out" v-if="itm.saleout">已抢光</view>
                        <!-- 尺码数量 -->
                        <view class="sku-num">
                            <view class="sku-list" v-if="itm.badge != 0">
                                <view v-for="(line, ii) in currentColors[idx].skus" :key="`${line.id}-${ii}`">
                                    <view class="border-bottom u-flex" v-if="line.num > 0">
                                        <text class="sku-sub-left">{{ line.sizeName || '默认' }}</text>
                                        <text class="sku-sub-center"> * </text>
                                        <text class="sku-sub-right">{{ line.num }}</text>
                                    </view>
                                </view>
                            </view>
                            <view v-else class="sku-num-undefined"> 您暂未选择此商品 </view>
                        </view>
                    </view>
                </view>
            </view>

            <view class="holder" :style="{ height: bottomBarHeight + 'px' }"></view>
            <!-- 按钮 -->
            <view class="action-btns safe-area-inset-bottom">
                <view class="u-p-t-20 u-p-b-20">
                    <!-- 如果从详情 商品内容中的规格进入-->
                    <view class="u-m-l-20 u-m-r-20 u-flex" v-if="btnType == 3">
                        <u-button type="s" :hair-line="false" class="u-flex-1" @click="add2cart">加入进货车</u-button>
                        <u-button type="p" class="u-flex-1 u-m-l-20" @click="buy">立即购买</u-button>
                    </view>
                    <!-- 点击加入购物车 -->
                    <view class="u-m-l-20 u-m-r-20 u-flex" v-if="btnType == 0">
                        <!-- <u-button type="d" @click="applySample" v-if="showBtnSample && !isVisitor" class="o-margin-right-sm">现货拿样</u-button> -->
                        <u-button type="p" class="u-flex-1" @click="add2cart">加入进货车</u-button>
                    </view>
                    <!-- 点击立即购买 -->
                    <view class="u-m-l-20 u-m-r-20 u-flex" v-if="btnType == 1">
                        <!-- <u-button type="d" @click="applySample" v-if="showBtnSample && !isVisitor" class="o-margin-right-sm">现货拿样</u-button> -->
                        <u-button type="p" @click="buy" class="u-flex-1">立即购买</u-button>
                    </view>
                    <!-- 虚拟商品 -->
                    <view class="u-m-l-20 u-m-r-20 u-flex" v-if="btnType == 2">
                        <u-button type="p" @click="buy" :hair-line="false" class="u-flex-1">立即购买</u-button>
                    </view>
                    <!-- 进货车页面 进来 -->
                    <view class="u-p-x-20" v-if="btnType == 4">
                        <u-button type="p" @click="changeCartNumber">确认</u-button>
                    </view>
                    <!-- 订单确认页 过来 -->
                    <view class="u-p-x-20" v-if="btnType == 5">
                        <u-button type="p" @click="returnToOrderConfirm">确认</u-button>
                    </view>
                </view>
            </view>
        </view>
        <!-- <kxj-previewImage ref="previewImage" :imgs="imgs" :desc="desc" /> -->
    </view>
</template>

<script lang="ts" setup>
import { onLoad, onReady } from '@dcloudio/uni-app'
import { computed, onMounted, ref } from 'vue'
import { useSkuCuntStore, useUserStore, useGlobalStore } from '@/store'
import global from '@/config'

/** 存放每个颜色的详细数据 */
const list = ref<Array<any>>([])
/** 当前选择的领型 key */
const currentCollar = ref('')
/**  */
const current = ref(0)
/** 0:实物商品  1:虚拟商品 */
const type = ref(0)
/** 是否显示 申请样品的按钮 */
// const showBtnSample = ref(false)

const topBarHeight = ref(72)
const bottomBarHeight = ref(120)
/*
 *   选中的商品内容, 每次数量变化时  修改这个数组
 *   下标为领型颜色对应的下标 属性名 为 skuId  值为数量 举例:selectGood[领型][颜色][skuId] = num
 */
// const selectGood = ref<Array<any>>([])

const btnType = ref(-1)
/** 预览图数组 */
// const imgs = ref([])
/** 预览图描述数组 */
// const desc = ref([])

/** Map 结构 存放 剩余购买数量 */
let remain = new Map()
/** spuid Set() */
let spuIds = new Set()
let releaseId: undefined | number | string = undefined
let goodName: undefined | string = undefined
/** 是否需要在卸载以页面的时候 保存规格数据 */
let noMoreSave = false
/** 订单类型 */
let orderType = 0
let previewArr: Map<string, any> = new Map()
let previewDesc: Map<string, any> = new Map()
/** 是否需要填充 已选规格的数量 */
let needMatch = false

const skuCountStore = useSkuCuntStore()
const userStore = useUserStore()
const globalStore = useGlobalStore()

// const previewImage = ref<any>(null)

const $u = computed(() => {
    return uni.$u
})
/** 当前访问用户是否为游客身份 */
const isVisitor = computed(() => {
    return userStore.userInfo.type == 3
})

const userId = computed(() => {
    return userStore.userInfo.id
})

const memberId = computed(() => {
    return userStore.userInfo.memberId
})
/** 合计所选商品总数 */
const summaryCount = computed(() => {
    let total = 0
    skuCountStore.colorBtns.forEach(entry => {
        entry.map((m: any) => {
            // console.log(m)
            total += m.badge
        })
    })
    return total
})
/** 选择的商品 总价 */
const summaryPrice = computed(() => {
    return 0
})
/** 领型数组 */
const collars = computed<Array<any>>(() => {
    return skuCountStore.collars
})
/** 选择颜色的 宽度 */
const ColorBtnWidth = computed(() => {
    const sys = uni.getSystemInfoSync()
    return Math.floor((sys.screenWidth - 50) / 3) + 'px'
})

const getLimitState = computed(() => {
    return function (item: any) {
        return remain.has(item.spuId) && item.badge > remain.get(item.spuId).count
    }
})
/** 当前勾选的领型下的 颜色数组 */
const currentColors = computed<any[]>(() => {
    return colorBtns.value.get(currentCollar.value)
})

/** 已选的规格 数组 */
const selectList = computed(() => {
    return skuCountStore.selectList
})

const colorBtns = computed(()=>{
    return skuCountStore.colorBtns
})

onLoad((option: any) => {
    let { id, status, mType, match, mOrderType } = JSON.parse(option.param)
    // 从商品详情进来的时候 有id
    releaseId = id
    /*
     *  btnType : 控制 页面 按钮
     */
    btnType.value = status
    type.value = mType // 商品类型  虚拟 OR 实物

    // 控制申请样品按钮 是否出现
    // if (!mShowBtnSample) showBtnSample.value = false
    // 是否 需要匹配已选规格数量
    if (match) needMatch = true
    if (mOrderType == 1) orderType = 1
})

onMounted(() => {
    // 获取 顶部 高度
    uni.$u.getRect('.top-bar').then((res: any) => {
        topBarHeight.value = res.height
    })
    // 底部高度
    uni.$u.getRect('.action-btns').then((res: any) => {
        bottomBarHeight.value = res.height
    })
})

onReady(() => {
    uni.$u.$api.GoodsApi.queryGoodsReleaseInfo({ id: releaseId }).then((res: any) => {
        // 获得 商品 源数据
        let skuVo = new Map(Object.entries(res.goodsReleaseSkuVo))
        goodName = res.goodsRelease.releaseName
        uni.setNavigationBarTitle({
            title: res.goodsRelease.releaseName
        })
        // 遍历领型
        for (let entry of skuVo) {
            let [key, value]: [key: string, value: any] = entry
            // 将 value.goodsReleaseSkuVo 转为Map 结构
            value.goodsReleaseSkuVo = new Map(Object.entries(value.goodsReleaseSkuVo))
            value.goodsReleaseSkuVo.forEach((Arr: Array<any>) => {
                Arr.forEach((sku: any) => {
                    if (!value.modelNo) value.modelNo = sku.modelNo
                    if (!value.spuId) value.spuId = sku.spuId
                    if (!value.releaseId) value.releaseId = releaseId
                    if (!value.goodsName) value.goodsName = goodName
                    if (!value.modelType) value.modelType = sku.modelTypeName
                    if (!value.userPrice) value.userPrice = sku.userPrice
                    // 设置 默认的领型
                    if (!currentCollar.value) currentCollar.value = sku.collarName
                    value.badge = 0
                    value.name = key
                    spuIds.add(sku.spuId)
                    delete sku.collarImage
                    delete sku.collarSort
                    delete sku.colorSort
                    delete sku.sizeSort
                    delete sku.saleNum
                    sku.picId = sku.picIds && sku.picIds[0]
                    delete sku.picIds
                    if (!sku.num) sku.num = 0
                })
            })
        }
        // 分三种情况
        // 1.从商品详情  或者直接从首页进来
        // 2.从购物车页面进来
        // 3.从订单确认页面进来
        queryVipLimited().catch(e => {
            console.log(e)
        })
        // 会员限购查询
        if (needMatch) {
            let source: any = globalStore.data
            matchData(skuVo, source.skus)
        } else {
            // #ifdef APP
            queryLocalSql(skuVo).then((res: any) => {
                skuCountStore.updateGood(res)
            })
            // #endif
            // ↓ 纯粹是为了便于 H5 调试
            // #ifndef APP
            skuCountStore.updateGood(skuVo)
            // #endif
        }

        // 处理 图片预览数组
        previewsInit()
    })
})

function previewsInit() {
    colorBtns.value.forEach((Arr: any[], key: any)=>{
        previewArr.set(key,Arr.map((m: any)=>`${global.productImageUrl}${m.picId}/0`))
        //todo 预览描述
    })
}
/** 返回订单确认页 */
function returnToOrderConfirm() {
    if (summaryCount.value == 0) {
        uni.$u.toast('请至少选择一件商品')
        return
    }

    uni.$emit('updateOrder', collars.value)
    uni.$u.$MRouter.back()
}

function changeCartNumber() {
    if (summaryCount.value == 0) {
        uni.$u.toast('请至少选择一件商品')
        return
    }
    if (!checkRemainCount()) return
    let res: Array<any> = []
    selectList.value.map((item: any) => {
        res.push({
            num: item.num,
            releaseId: releaseId,
            releaseSkuId: item.id
        })
    })
    uni.$emit('changeCount', res)
    uni.navigateBack()
}

// 检查限购数量
function checkRemainCount() {
    console.log('检查限购:', remain);
    // 验证 是否超出限购数量
    for (let entry of remain) {
        // let a = eval(this.selectList.filter(m => m.spuId == key).map(item => item.num).join('+'))
        // if (a > this.remain[key].count) {
        //     uni.$u.toast('存在商品超出限购数量,请修改数量!')
        //     return false
        // }
    }
    return true
}

/** 查询会员限购 */
function queryVipLimited() {
    return new Promise((resolve, reject) => {
        if (isVisitor.value) {
            console.info('当前是游客身份')
            reject()
        } else {
            if (memberId.value) {
                uni.$u.$api.MemberApi.queryMemberRestriction({
                    memberId: memberId.value,
                    spuIds: [...spuIds].join(',')
                }).then((req: any) => {
                    req.map((m: any) => {
                        remain.set(m.spuId, {
                            count: m.restrictionNum - m.purchasedNum
                        })
                    })
                    // console.log('限购情况: ', this.remain);
                    resolve('')
                })
            } else {
                console.info('当前是非会员身份')
                reject()
            }
        }
    })
}
/**
 * 将已有数量的数据 覆盖规格数据
 * @param {Object} skuVo  商品对象 包含所有领型 颜色 尺码
 * @param {Object} skus 从购物车 或者订单确认页面进来时  已经勾选的 带数量的 规格数据
 */
function matchData(skuVo: any, skus: any) {
    let skuIds = new Map()
    skus.filter((m: any)=> m.num>0).map((m: any) => {
        skuIds.set(Number(m.skuId), m.num)
    })
    //todo 双重循环 有优化条件
    for (let [key,collar] of skuVo) {
        for (let [key2, colors] of collar.goodsReleaseSkuVo) {
            for (let sku of colors) {
                if (skuIds.has(Number(sku.skuId))) {
                    // 初始化 默认数量
                    let target = skuIds.get(Number(sku.skuId))
                    sku.num = target
                }
            }
        }
    }
    // 从购物车 或者订单确认页面 进来时  不需要保存临时数据
    noMoreSave = true
    skuCountStore.updateGood(skuVo)
}
/** 设置当前选择的领型名称 用于选择对应的领型的颜色分组 */
function setCollarNum(name: string) {
    if (name != currentCollar.value) currentCollar.value = name
}

/** 切换颜色 */
function changeColor(idx: number | string, item: any) {
    // 将点击的颜色存储到 store 中
    skuCountStore.updateCurrentColor(item)
    let para: any = {
        current: idx, // 颜色下标
        orderType: orderType,
        goodName: item.skus[0].goodsName, // 商品名称
        index: currentCollar.value // 领型下标
    }
    if (remain.size > 0) {
        let key = item.skus[0].spuId
        para.remain = JSON.stringify(remain.get(key))
    }
    uni.$u.$MRouter.skuCountEditSub.to(para)
}

/** 查询本地数据 */
function queryLocalSql(skuVo: Map<string, any>) {
    return new Promise((resolve, reject) => {
        uni.$u.$imHandler.sku.getHistoryList(releaseId, userId.value).then((res: any) => {
                let skuIds = res.map((m: any) => Number(m.skuId))
                outer:
                for (let [key,value] of skuVo) {
                    for (let [key2, colors] of value.goodsReleaseSkuVo) {
                        for (let sku of colors) {
                            if (skuIds.indexOf(Number(sku.skuId)) > -1) {
                                // 初始化 默认数量
                                let target = res.filter((i: any) => i.skuId == sku.skuId)[0]
                                sku.num = target.count
                                sku.localSQLID = target.id
                                break outer;
                            }
                        }
                    }
                }
                resolve(skuVo)
            }).catch(() => {
                console.log('查询出错');
                resolve(skuVo)
        })
    })
}
/** 大图预览 */
function showPreview(n: number) {
    console.log('当前选择的领型: ', currentCollar.value, '图片序号: ', n);
    // imgs.value = previewArr[currentCollar.value]
    // desc.value = previewDesc[currentCollar.value]
    // uni.showLoading({
    //     mask: true,
    //     title: '请稍后...'
    // })
    // setTimeout(() => {
    //     previewImage.value?.open(n)
    //     uni.hideLoading()
    // }, 300)
}

function add2cart() {}

function buy() {}
</script>

<style scoped lang="scss">
@import './common.scss';
</style>
